Current Sprint: 3. 遊戲基本流程完成
repo: https://github.com/side-project-at-SPT/ithome-ironman-2024-san-juan
swagger docs: https://side-project-at-spt.github.io/ithome-ironman-2024-san-juan/
礦工
階段行動議員
階段行動建築師
階段行動製造商
階段行動貿易商
階段行動 def play
@game = Game.find(params[:id])
@game.play
return render status: :unprocessable_entity, json: { error: @game.errors.full_messages } if @game.errors.any?
@message = "你選擇了礦工"
end
根據 Day 15 定義的 api format
POST /api/v1/games/{id}/roles/{role}
下面來更新他
# config/routes.rb
Rails.application.routes.draw do
# ...
namespace :api do
namespace :v1 do
resources :games, only: [ :index, :create ] do
member do
post :play
scope :roles do
post ":role", action: :assign, as: :assign_role
end
end
end
end
end
end
# app/controllers/api/v1/game_controller.rb
class Api::V1::GamesController < ApplicationController
# ...
def assign
@game = Game.find(params[:id])
@current_player ||= "dummy player"
@game.assign_role(role: params[:role], player: @current_player)
if @game.errors.any?
return render status: :unprocessable_entity, json: {
error: @game.errors.full_messages
}
end
@message = "你選擇了: #{params[:role]}"
render json: { message: @message }
end
# ...
end
# app/models/game.rb
class Game < ApplicationRecord
# ...
def assign_role(role:, player:)
return errors.add(:status, "can't be blank") unless status_playing?
roles = {
"builder" => "建築師",
"producer" => "製造商",
"trader" => "貿易商",
"prospector" => "礦工",
"councillor" => "議員"
}
return errors.add(:role, "#{role} is invalid") unless (roles.keys + roles.values).include?(role)
self
end
# ...
end
# rails s
curl localhost:3000/api/v1/games -d '' | jq
# {
# "id": 6,
# "status": "playing",
# ...
curl localhost:3000/api/v1/games/6/roles/戰士 -d '' | jq
# {
# "error": [
# "Role 戰士 is invalid"
# ]
# }
curl localhost:3000/api/v1/games/6/roles/礦工 -d '' | jq
# {
# "message": "你選擇了: 礦工"
# }
明天把選職業的方法寫完
礦工
階段行動議員
階段行動建築
階段行動生產
階段行動交易
階段行動礦工
階段行動議員
階段行動以上不代表明天會做,如有雷同純屬巧合
SPT (Side Project Taiwan) 的宗旨是藉由Side Project開發來成就自我,透過持續學習和合作,共同推動技術和專業的發展。我們相信每一個參與者,無論是什麼專業,都能在這個社群中找到屬於自己的成長空間。
歡迎所有對Side Project開發有興趣的人加入我們,可以是有點子來找夥伴,也可以是來尋找有興趣的Side Project加入,邀請大家一同打造一個充滿活力且有意義的技術社群!
Discord頻道連結: https://sideproj.tw/dc